package app.com;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import app.com.adapter.ClassmateAdapter;
import app.com.pojo.Classmate;

public class MainActivity extends AppCompatActivity {

    ListView lv_classmate;
    List<Classmate> classmateList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();

//        List<Classmate> list= new ArrayList<Classmate>();
//        Classmate m1= new Classmate();
//        m1.setName("张三");
//        Classmate m2= new Classmate();
//        m2.setName("李四");
//
//        list.add(m1);
//        list.add(m2);

        network();


    }

    private void network() {
        String url="http://10.2.64.12:8080/app3/classmate/list";

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        JsonObjectRequest jsonObjectRequest =new JsonObjectRequest(Request.Method.POST, url, (JSONObject) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    JSONArray list = jsonObject.getJSONArray("list");
//                    System.out.println(list);
                    Gson gson = new Gson();
                    List<Classmate> classmateList=gson.fromJson(list.toString(),new TypeToken<List<Classmate>>(){
                    }.getType());

                    ClassmateAdapter adapter = new ClassmateAdapter(MainActivity.this,classmateList);
                    lv_classmate.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("请求失败");
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    private void init() {
        lv_classmate=(ListView)findViewById(R.id.lv_classmate);
    }
}